package cn.edu.zafu.bigdata.smj.e;

import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeServer {
    public static void main(String[] args) {
        int port = 12345; // 服务端监听的端口
        try (DatagramSocket serverSocket = new DatagramSocket(port)) {
            System.out.println("时间同步服务端已启动，等待客户端请求...");
            byte[] receiveBuffer = new byte[1024];
            byte[] sendBuffer;

            while (true) {
                // 接收客户端请求
                DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
                serverSocket.receive(receivePacket);
                String clientMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
                System.out.println("收到客户端请求：" + clientMessage);

                // 获取当前时间
                String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                sendBuffer = currentTime.getBytes();

                // 发送当前时间给客户端
                InetAddress clientAddress = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();
                DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, clientAddress, clientPort);
                serverSocket.send(sendPacket);

                System.out.println("已发送时间：" + currentTime);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

